package com.xky.ui.module.salesManagement.update;

import com.xky.pojo.SalesOrders;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder;
import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.Timer;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

/**
 * 修改销售订单信息的窗口类
 */
public class UpdateSalesOrder extends JFrame {
    private JPanel mainPanel, formPanel, buttonPanel;
    private JTextField orderNumberField, orderDateField,
            expectedShipDateField, actualShipDateField, warehouseIdField,
            taxAmountField, discountAmountField, totalAmountField,
            paidAmountField;
    private JComboBox<String> orderStatusCombo, paymentStatusCombo;
    private JTextArea notesArea;
    private JButton searchButton, updateButton, cancelButton;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color CANCEL_BUTTON_COLOR = new Color(231, 76, 60);
    
    // 日期格式化
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 当前编辑的订单
    private SalesOrders currentOrder;
    private boolean readOnly;

    public UpdateSalesOrder() {
        this(-1);
    }

    public UpdateSalesOrder(int orderId) {
        this(orderId, false);
    }
    
    public UpdateSalesOrder(int orderId, boolean readOnly) {
        this.readOnly = readOnly;
        setTitle(readOnly ? "查看销售订单信息" : "修改销售订单信息");
        setSize(550, 880);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        // 添加窗口图标
        try {
            ImageIcon icon = new ImageIcon(getClass().getResource("/icons/order_icon.png"));
            if (icon.getIconWidth() > 0) {
                setIconImage(icon.getImage());
            }
        } catch (Exception e) {
            // 图标加载失败，忽略
        }
        
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        init();
        
        if (orderId > 0) {
            // 隐藏搜索面板
            orderNumberField.setEnabled(false);
            searchButton.setEnabled(false);
            Component[] components = mainPanel.getComponents();
            for (Component component : components) {
                if (component instanceof JPanel) {
                    JPanel panel = (JPanel) component;
                    if (panel.getLayout() instanceof BorderLayout) {
                        Component centerComponent = ((BorderLayout) panel.getLayout()).getLayoutComponent(BorderLayout.CENTER);
                        if (centerComponent instanceof JPanel) {
                            Component searchCard = ((JPanel) centerComponent).getComponent(0);
                            if (searchCard instanceof JPanel) {
                                searchCard.setVisible(false);
                            }
                        }
                    }
                }
            }

            // 显示加载动画
            JDialog waitingDialog = showWaitingDialog("正在加载订单信息...");
            
            // 在后台线程中执行查询
            SwingWorker<SalesOrders, Void> worker = new SwingWorker<>() {
                @Override
                protected SalesOrders doInBackground() {
                    try {
                        List<SalesOrders> orders = SelectSalesOrder.selectById(orderId);
                        return !orders.isEmpty() ? orders.get(0) : null;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        return null;
                    }
                }

                @Override
                protected void done() {
                    waitingDialog.dispose();
                    try {
                        currentOrder = get();
                        if (currentOrder != null) {
                            populateForm(currentOrder);
                            setFormFieldsEnabled(!readOnly);
                            
                            // 添加淡入效果
                            fadeInComponent(formPanel);
                        } else {
                            showWarning("未找到订单编号为 " + orderId + " 的订单记录");
                            clearForm();
            setFormFieldsEnabled(false);
                        }
                    } catch (Exception ex) {
                        showError("加载订单时发生错误: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                }
            };
            worker.execute();
        }

        // 添加窗口关闭确认
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                    dispose();
            }
        });
        
        setVisible(true);
    }
    
    private void init() {
        // 创建主面板并设置背景渐变
        mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 顶部标题面板
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
        
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel("修改销售订单信息");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(PRIMARY_COLOR);
        // 添加标题阴影效果
        titleLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(0, 0, 5, 0),
                BorderFactory.createEmptyBorder(0, 0, 0, 0)
        ));
        titlePanel.add(titleLabel);
        
        JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        hintPanel.setOpaque(false);
        
        JLabel hintLabel = new JLabel("请输入订单编号查询后再修改");
        hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        hintLabel.setForeground(Color.GRAY);
        hintPanel.setPreferredSize(new Dimension(100, 30));
        hintPanel.add(hintLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                
                int width = getWidth();
                int height = getHeight();
                
                // 创建渐变
                GradientPaint gradient = new GradientPaint(
                    0, 0, new Color(PRIMARY_COLOR.getRed(), PRIMARY_COLOR.getGreen(), PRIMARY_COLOR.getBlue(), 50),
                    width, 0, new Color(PRIMARY_COLOR.getRed(), PRIMARY_COLOR.getGreen(), PRIMARY_COLOR.getBlue(), 200)
                );
                
                g2d.setPaint(gradient);
                g2d.fillRect(0, 0, width, height);
            }
        };
        separator.setPreferredSize(new Dimension(450, 2));
        
        headerPanel.add(titlePanel, BorderLayout.NORTH);
        headerPanel.add(hintPanel, BorderLayout.CENTER);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        // 中部搜索和表单面板
        JPanel centerPanel = new JPanel(new BorderLayout(0, 15));
        centerPanel.setOpaque(false);
        
        // 搜索面板
        JPanel searchCard = createRoundedPanel();
        searchCard.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 15));
        
        JLabel searchLabel = new JLabel("订单编号");
        searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        searchLabel.setForeground(PRIMARY_COLOR);
        searchCard.add(searchLabel);

        orderNumberField = new JTextField(15);
        orderNumberField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        orderNumberField.setPreferredSize(new Dimension(200, 35));
        // 添加文本框边框效果
        orderNumberField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(5, 8, 5, 8)
        ));
        searchCard.add(orderNumberField);
        
        searchButton = new JButton("查询");
        styleButton(searchButton, QUERY_BUTTON_COLOR);
        searchButton.setPreferredSize(new Dimension(100, 35));
        searchCard.add(searchButton);
        
        centerPanel.add(searchCard, BorderLayout.NORTH);

        // 表单面板
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        
        formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);
        
        // 创建表单字段
        createFormFields();

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(formPanel);
        scrollPane.setBorder(null);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        
        formCard.add(scrollPane, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        centerPanel.add(formCard, BorderLayout.CENTER);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        
        // 底部按钮面板
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);
        
        updateButton = new JButton("更新");
        styleButton(updateButton, BUTTON_COLOR);
        
        cancelButton = new JButton("取消");
        styleButton(cancelButton, CANCEL_BUTTON_COLOR);
        
        buttonPanel.add(updateButton);
        buttonPanel.add(cancelButton);
        
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
        
        // 禁用表单字段，直到用户搜索到订单
        setFormFieldsEnabled(false);
        
        // 添加事件监听器
        addEventListeners();
    }
    
    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
                
                // 添加微妙的内阴影效果
                g2d.setColor(new Color(0, 0, 0, 10));
                g2d.drawRoundRect(1, 1, getWidth() - 3, getHeight() - 3, 15, 15);
            }
        };
        panel.setOpaque(false);

        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));

        return panel;
    }
    
    private void styleButton(JButton button, Color bgColor) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(120, 40));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(
                    Math.max((int)(bgColor.getRed() * 0.9), 0),
                    Math.max((int)(bgColor.getGreen() * 0.9), 0),
                    Math.max((int)(bgColor.getBlue() * 0.9), 0)
                ));
            }
            
            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(bgColor);
            }
            
            @Override
            public void mousePressed(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(
                    Math.max((int)(bgColor.getRed() * 0.8), 0),
                    Math.max((int)(bgColor.getGreen() * 0.8), 0),
                    Math.max((int)(bgColor.getBlue() * 0.8), 0)
                ));
            }
            
            @Override
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(
                    Math.max((int)(bgColor.getRed() * 0.9), 0),
                    Math.max((int)(bgColor.getGreen() * 0.9), 0),
                    Math.max((int)(bgColor.getBlue() * 0.9), 0)
                ));
            }
        });
    }
    
    /**
     * 创建表单字段
     */
    private void createFormFields() {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 10, 10, 10);

        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);

        // 创建并添加字段
        orderDateField = createStyledTextField(fieldFont);
        orderDateField.setToolTipText("格式：yyyy-MM-dd ");
        
        expectedShipDateField = createStyledTextField(fieldFont);
        expectedShipDateField.setToolTipText("格式：yyyy-MM-dd");
        
        actualShipDateField = createStyledTextField(fieldFont);
        actualShipDateField.setToolTipText("格式：yyyy-MM-dd");
        
        warehouseIdField = createStyledTextField(fieldFont);
        warehouseIdField.setToolTipText("输入仓库ID，必须为整数");
        
        taxAmountField = createStyledTextField(fieldFont);
        taxAmountField.setToolTipText("输入税额，例如：10.00");
        
        discountAmountField = createStyledTextField(fieldFont);
        discountAmountField.setToolTipText("输入折扣金额，例如：5.00");
        
        totalAmountField = createStyledTextField(fieldFont);
        totalAmountField.setToolTipText("输入总金额，例如：105.00");
        
        paidAmountField = createStyledTextField(fieldFont);
        paidAmountField.setToolTipText("输入已付金额，例如：50.00");

        // 创建下拉框
        String[] orderStatuses = {"待处理", "已确认", "已发货", "已完成", "已取消"};
        orderStatusCombo = new JComboBox<>(orderStatuses);
        styleComboBox(orderStatusCombo, fieldFont);
        orderStatusCombo.setToolTipText("选择订单状态");

        String[] paymentStatuses = {"未支付", "部分支付", "已支付", "已退款"};
        paymentStatusCombo = new JComboBox<>(paymentStatuses);
        styleComboBox(paymentStatusCombo, fieldFont);
        paymentStatusCombo.setToolTipText("选择支付状态");

        // 创建备注文本区域
        notesArea = new JTextArea(4, 20);
        notesArea.setFont(fieldFont);
        notesArea.setLineWrap(true);
        notesArea.setWrapStyleWord(true);
        notesArea.setToolTipText("输入订单备注信息");
        JScrollPane notesScrollPane = new JScrollPane(notesArea);
        notesScrollPane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));

        // 添加字段到面板
        int row = 0;
        addFormField(row++, "下单日期 *", orderDateField, labelFont);
        addFormField(row++, "预计发货日期", expectedShipDateField, labelFont);
        addFormField(row++, "实际发货日期", actualShipDateField, labelFont);
        addFormField(row++, "仓库ID *", warehouseIdField, labelFont);
        addFormField(row++, "订单状态 *", orderStatusCombo, labelFont);
        addFormField(row++, "支付状态 *", paymentStatusCombo, labelFont);
        addFormField(row++, "税额", taxAmountField, labelFont);
        addFormField(row++, "折扣金额", discountAmountField, labelFont);
        addFormField(row++, "总金额 *", totalAmountField, labelFont);
        addFormField(row++, "已付金额", paidAmountField, labelFont);
        addFormField(row++, "备注", notesScrollPane, labelFont);
        
        // 添加字段值变化监听器
        addFieldChangeListeners();
    }

    // 添加字段值变化监听器，用于自动计算总金额
    private void addFieldChangeListeners() {
        // 税额、折扣金额变化时自动计算总金额
        DocumentListener amountChangeListener = new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                updateTotalAmount();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateTotalAmount();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateTotalAmount();
            }
        };
        
        // 添加监听器
        if (taxAmountField != null) {
            taxAmountField.getDocument().addDocumentListener(amountChangeListener);
        }
        if (discountAmountField != null) {
            discountAmountField.getDocument().addDocumentListener(amountChangeListener);
        }
    }
    
    // 自动计算总金额
    private void updateTotalAmount() {
        try {
            // 直接使用税额和折扣金额计算总金额
            BigDecimal taxAmount = new BigDecimal(taxAmountField.getText().trim().isEmpty() ? "0" : taxAmountField.getText().trim());
            BigDecimal discountAmount = new BigDecimal(discountAmountField.getText().trim().isEmpty() ? "0" : discountAmountField.getText().trim());
            
            // 总金额 = 税额 + 商品金额 - 折扣
            // 注：实际业务中，通常总金额应该是基础金额加税额减折扣，这里假设基础金额已经包含在当前总金额中
            BigDecimal currentTotal = totalAmountField.getText().trim().isEmpty() ? 
                BigDecimal.ZERO : new BigDecimal(totalAmountField.getText().trim());
            BigDecimal baseAmount = currentTotal.add(discountAmount).subtract(taxAmount);
            
            // 重新计算总金额
            BigDecimal total = baseAmount.add(taxAmount).subtract(discountAmount);
            if (total.compareTo(BigDecimal.ZERO) < 0) {
                total = BigDecimal.ZERO; // 确保总金额不为负
            }
            totalAmountField.setText(total.toString());
        } catch (NumberFormatException e) {
            // 忽略非数字输入
        }
    }

    private JTextField createStyledTextField(Font font) {
        JTextField field = new JTextField();
        field.setFont(font);
        field.setPreferredSize(new Dimension(250, 35));
        
        // 添加焦点效果
        field.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                field.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(PRIMARY_COLOR, 2),
                        BorderFactory.createEmptyBorder(5, 8, 5, 8)
                ));
            }
            
            @Override
            public void focusLost(java.awt.event.FocusEvent evt) {
                field.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(200, 200, 200)),
                        BorderFactory.createEmptyBorder(5, 8, 5, 8)
                ));
            }
        });
        
        // 设置初始边框
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(5, 8, 5, 8)
        ));
        
        return field;
    }

    private void styleComboBox(JComboBox<String> comboBox, Font font) {
        comboBox.setFont(font);
        comboBox.setPreferredSize(new Dimension(250, 35));
        comboBox.setBackground(Color.WHITE);
        
        // 设置圆角边框
        comboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(5, 8, 5, 8)
        ));
        
        // 添加焦点效果
        comboBox.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                comboBox.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(PRIMARY_COLOR, 2),
                        BorderFactory.createEmptyBorder(5, 8, 5, 8)
                ));
            }
            
            @Override
            public void focusLost(java.awt.event.FocusEvent evt) {
                comboBox.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(200, 200, 200)),
                        BorderFactory.createEmptyBorder(5, 8, 5, 8)
                ));
            }
        });
    }

    private void addFormField(int row, String labelText, JComponent field, Font labelFont) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.weightx = 0.3;

        JLabel label = new JLabel(labelText);
        label.setFont(labelFont);
        label.setForeground(PRIMARY_COLOR);
        formPanel.add(label, gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        formPanel.add(field, gbc);
    }

    private void populateForm(SalesOrders order) {
        if (order == null) return;

        orderDateField.setText(order.getOrderDate() != null ? order.getOrderDate().format(DATETIME_FORMATTER) : "");
        expectedShipDateField.setText(order.getExpectedShipDate() != null ? order.getExpectedShipDate().format(DATE_FORMATTER) : "");
        actualShipDateField.setText(order.getActualShipDate() != null ? order.getActualShipDate().format(DATE_FORMATTER) : "");
        warehouseIdField.setText(String.valueOf(order.getWarehouseId()));
        orderStatusCombo.setSelectedItem(order.getOrderStatus());
        paymentStatusCombo.setSelectedItem(order.getPaymentStatus());
        taxAmountField.setText(order.getTaxAmount() != null ? order.getTaxAmount().toString() : "0");
        discountAmountField.setText(order.getDiscountAmount() != null ? order.getDiscountAmount().toString() : "0");
        totalAmountField.setText(order.getTotalAmount() != null ? order.getTotalAmount().toString() : "0");
        paidAmountField.setText(order.getPaidAmount() != null ? order.getPaidAmount().toString() : "0");
        notesArea.setText(order.getNotes() != null ? order.getNotes() : "");

        // 更新总金额
        updateTotalAmount();

        setFormFieldsEnabled(!readOnly);
    }

    private void setFormFieldsEnabled(boolean enabled) {
        orderDateField.setEnabled(enabled);
        expectedShipDateField.setEnabled(enabled);
        actualShipDateField.setEnabled(enabled);
        warehouseIdField.setEnabled(enabled);
        orderStatusCombo.setEnabled(enabled);
        paymentStatusCombo.setEnabled(enabled);
        taxAmountField.setEnabled(enabled);
        discountAmountField.setEnabled(enabled);
        totalAmountField.setEnabled(enabled);
        paidAmountField.setEnabled(enabled);
        notesArea.setEnabled(enabled);
        updateButton.setEnabled(enabled && !readOnly);
    }


    /**
     * 显示等待对话框
     */
    private JDialog showWaitingDialog(String message) {
        JDialog dialog = new JDialog(this, "请稍候", false);
        dialog.setUndecorated(true);
        dialog.setLayout(new BorderLayout());
        dialog.setSize(300, 100);
        dialog.setLocationRelativeTo(this);
        
        // 创建半透明面板
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(new Color(255, 255, 255, 240));
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
                g2d.setColor(new Color(200, 200, 200));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setLayout(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        JLabel messageLabel = new JLabel(message, JLabel.CENTER);
        messageLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        messageLabel.setForeground(new Color(70, 70, 70));
        
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        progressBar.setPreferredSize(new Dimension(250, 5));
        progressBar.setBorderPainted(false);
        progressBar.setForeground(PRIMARY_COLOR);
        progressBar.setBackground(new Color(240, 240, 240));
        
        panel.add(messageLabel, BorderLayout.NORTH);
        panel.add(progressBar, BorderLayout.CENTER);
        
        dialog.add(panel);
        dialog.setVisible(true);
        
        return dialog;
    }

    private void showInfo(String message) {
        JOptionPane.showMessageDialog(this, message, "信息", JOptionPane.INFORMATION_MESSAGE);
    }

    private void showWarning(String message) {
        JOptionPane.showMessageDialog(this, message, "警告", JOptionPane.WARNING_MESSAGE);
    }

    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }


    private void addEventListeners() {
        // 查询按钮事件
        searchButton.addActionListener(e -> {
            String orderNumber = orderNumberField.getText().trim();
            if (orderNumber.isEmpty()) {
                showWarning("请输入订单编号");
                orderNumberField.requestFocus();
                return;
            }

            // 显示等待对话框
            JDialog waitingDialog = showWaitingDialog("正在查询订单信息...");

            // 在后台线程中执行查询
            SwingWorker<List<SalesOrders>, Void> worker = new SwingWorker<>() {
                @Override
                protected List<SalesOrders> doInBackground() {
                    try {
                        // 添加短暂延迟，让用户能看到加载动画
                        Thread.sleep(300);
                        return SelectSalesOrder.selectByOrderNumber(orderNumber);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        return null;
                    }
                }

                @Override
                protected void done() {
                    // 关闭等待对话框
                    waitingDialog.dispose();
                    
                    try {
                        List<SalesOrders> orders = get();
                        if (orders != null && !orders.isEmpty()) {
                            if (orders.size() > 1) {
                                // 如果找到多个匹配项，显示选择对话框
                                SalesOrders selected = showSelectionDialog(orders);
                                if (selected != null) {
                                    currentOrder = selected;
                                    populateForm(currentOrder);
                                    setFormFieldsEnabled(true);
                                    fadeInComponent(formPanel);
                                }
            } else {
                                // 只找到一个匹配项
                                currentOrder = orders.get(0);
                                populateForm(currentOrder);
                                setFormFieldsEnabled(true);
                                fadeInComponent(formPanel);
                            }
            } else {
                            showWarning("未找到订单编号包含 " + orderNumber + " 的记录");
                            clearForm();
                            setFormFieldsEnabled(false);
                        }
                    } catch (Exception ex) {
                        showError("查询订单时发生错误: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                }
            };
            worker.execute();
        });

        // 更新按钮事件
        updateButton.addActionListener(e -> {
            if (!validateForm()) {
                return;
            }

            int option = JOptionPane.showConfirmDialog(this,
                    "确定要更新此销售订单吗？", "确认更新",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (option != JOptionPane.YES_OPTION) {
                return;
            }

            // 显示等待对话框
            JDialog waitingDialog = showWaitingDialog("正在更新销售订单...");

            // 在后台线程中执行更新
            SwingWorker<Boolean, Void> worker = new SwingWorker<>() {
                private String errorMessage = null;
                
                @Override
                protected Boolean doInBackground() {
                    try {
                        updateOrderFromForm();
                        return true;
                    } catch (Exception ex) {
                        errorMessage = ex.getMessage();
                        ex.printStackTrace();
            return false;
                    }
                }

                @Override
                protected void done() {
                    // 关闭等待对话框
                    waitingDialog.dispose();
                    
                    try {
                        boolean success = get();
                        if (success) {
                            showInfo("销售订单更新成功！");
                            dispose();
                        } else {
                            showError(errorMessage != null ? errorMessage : "销售订单更新失败，请重试");
                        }
                    } catch (Exception ex) {
                        showError("更新订单时发生错误: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                }
            };
            worker.execute();
        });

        // 取消按钮事件
        cancelButton.addActionListener(e -> dispose());

        // 为订单编号文本框添加回车键事件
        orderNumberField.addActionListener(e -> searchButton.doClick());
    }

    /**
     * 显示选择对话框
     */
    private SalesOrders showSelectionDialog(List<SalesOrders> orders) {
        // 创建对话框
        JDialog dialog = new JDialog(this, "选择订单", true);
        dialog.setLayout(new BorderLayout(10, 10));
        dialog.setSize(800, 400);
        dialog.setLocationRelativeTo(this);

        // 创建表格模型
        String[] columnNames = {"订单ID", "订单编号", "客户ID", "下单日期", "订单状态", "支付状态", "总金额"};
        Object[][] data = new Object[orders.size()][7];
        for (int i = 0; i < orders.size(); i++) {
            SalesOrders order = orders.get(i);
            data[i][0] = order.getOrderId();
            data[i][1] = order.getOrderNumber();
            data[i][2] = order.getCustomerId();
            data[i][3] = order.getOrderDate() != null ? order.getOrderDate().format(DATETIME_FORMATTER) : "";
            data[i][4] = order.getOrderStatus();
            data[i][5] = order.getPaymentStatus();
            data[i][6] = order.getTotalAmount();
        }

        JTable table = new JTable(data, columnNames) {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component comp = super.prepareRenderer(renderer, row, column);
                
                // 设置交替行颜色
                if (!isRowSelected(row)) {
                    comp.setBackground(row % 2 == 0 ? Color.WHITE : new Color(245, 245, 250));
                } else {
                    comp.setBackground(new Color(210, 230, 255));
                }
                
                return comp;
            }
        };
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        table.getTableHeader().setBackground(PRIMARY_COLOR);
        table.getTableHeader().setForeground(Color.WHITE);
        table.setRowHeight(30);
        table.setShowGrid(false);
        table.setIntercellSpacing(new Dimension(0, 0));
        
        // 设置表格列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(60);
        table.getColumnModel().getColumn(1).setPreferredWidth(120);
        table.getColumnModel().getColumn(2).setPreferredWidth(60);
        table.getColumnModel().getColumn(3).setPreferredWidth(150);
        table.getColumnModel().getColumn(4).setPreferredWidth(80);
        table.getColumnModel().getColumn(5).setPreferredWidth(80);
        table.getColumnModel().getColumn(6).setPreferredWidth(100);
        
        // 居中显示内容
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        for (int i = 0; i < table.getColumnCount(); i++) {
            table.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
        }

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        dialog.add(scrollPane, BorderLayout.CENTER);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton selectButton = new JButton("选择");
        JButton cancelButton = new JButton("取消");

        // 设置按钮样式
        selectButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        selectButton.setPreferredSize(new Dimension(100, 35));
        cancelButton.setPreferredSize(new Dimension(100, 35));
        selectButton.setBackground(BUTTON_COLOR);
        selectButton.setForeground(Color.WHITE);
        cancelButton.setBackground(CANCEL_BUTTON_COLOR);
        cancelButton.setForeground(Color.WHITE);
        selectButton.setBorderPainted(false);
        cancelButton.setBorderPainted(false);
        selectButton.setFocusPainted(false);
        cancelButton.setFocusPainted(false);

        final SalesOrders[] selected = {null};

        selectButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                selected[0] = orders.get(selectedRow);
                dialog.dispose();
            } else {
                showWarning("请选择一个订单");
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(selectButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        // 添加双击事件
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    int row = table.rowAtPoint(evt.getPoint());
                    if (row >= 0) {
                        selected[0] = orders.get(row);
                        dialog.dispose();
                    }
                }
            }
        });

        // 显示对话框
        dialog.setVisible(true);

        return selected[0];
    }

    /**
     * 从表单更新订单对象
     */
    private void updateOrderFromForm() {
        if (currentOrder == null) {
            currentOrder = new SalesOrders();
        }

        try {
            // 处理日期字段
            if (!orderDateField.getText().trim().isEmpty()) {
                try {
                    currentOrder.setOrderDate(LocalDateTime.parse(orderDateField.getText().trim(), DATETIME_FORMATTER));
                } catch (DateTimeParseException e) {
                    throw new RuntimeException("下单日期格式不正确，请使用 yyyy-MM-dd HH:mm:ss 格式");
                }
            }
            
            if (!expectedShipDateField.getText().trim().isEmpty()) {
                try {
                    currentOrder.setExpectedShipDate(LocalDate.parse(expectedShipDateField.getText().trim(), DATE_FORMATTER));
                } catch (DateTimeParseException e) {
                    throw new RuntimeException("预计发货日期格式不正确，请使用 yyyy-MM-dd 格式");
                }
            }
            
            if (!actualShipDateField.getText().trim().isEmpty()) {
                try {
                    currentOrder.setActualShipDate(LocalDate.parse(actualShipDateField.getText().trim(), DATE_FORMATTER));
                } catch (DateTimeParseException e) {
                    throw new RuntimeException("实际发货日期格式不正确，请使用 yyyy-MM-dd 格式");
                }
            }
            
            currentOrder.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim()));
            currentOrder.setOrderStatus((String) orderStatusCombo.getSelectedItem());
            currentOrder.setPaymentStatus((String) paymentStatusCombo.getSelectedItem());
            
            // 处理金额字段
            if (!taxAmountField.getText().trim().isEmpty()) {
                try {
                    currentOrder.setTaxAmount(new BigDecimal(taxAmountField.getText().trim()));
                } catch (NumberFormatException e) {
                    throw new RuntimeException("税额格式不正确，请输入有效的数字");
                }
            }
            
            if (!discountAmountField.getText().trim().isEmpty()) {
                try {
                    currentOrder.setDiscountAmount(new BigDecimal(discountAmountField.getText().trim()));
                } catch (NumberFormatException e) {
                    throw new RuntimeException("折扣金额格式不正确，请输入有效的数字");
                }
            }
            
            if (!totalAmountField.getText().trim().isEmpty()) {
                try {
                    currentOrder.setTotalAmount(new BigDecimal(totalAmountField.getText().trim()));
                } catch (NumberFormatException e) {
                    throw new RuntimeException("总金额格式不正确，请输入有效的数字");
                }
            }
            
            if (!paidAmountField.getText().trim().isEmpty()) {
                try {
                    currentOrder.setPaidAmount(new BigDecimal(paidAmountField.getText().trim()));
                } catch (NumberFormatException e) {
                    throw new RuntimeException("已付金额格式不正确，请输入有效的数字");
                }
            }
            
            currentOrder.setNotes(notesArea.getText().trim());
            
            // 更新数据库
            saveOrderToDatabase();
            
        } catch (NumberFormatException e) {
            throw new RuntimeException("请检查数字字段格式是否正确: " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("更新订单时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 将订单保存到数据库
     */
    private void saveOrderToDatabase() {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = DBUtils.getConnection();
            String sql = "UPDATE sales_orders SET order_date=?, expected_ship_date=?, " +
                        "actual_ship_date=?, warehouse_id=?, order_status=?, payment_status=?, " +
                        "tax_amount=?, discount_amount=?, total_amount=?, paid_amount=?, " +
                        "notes=?, updated_time=? WHERE order_id=?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(1, currentOrder.getOrderDate() != null ? Timestamp.valueOf(currentOrder.getOrderDate()) : null);
            pstmt.setDate(2, currentOrder.getExpectedShipDate() != null ? java.sql.Date.valueOf(currentOrder.getExpectedShipDate()) : null);
            pstmt.setDate(3, currentOrder.getActualShipDate() != null ? java.sql.Date.valueOf(currentOrder.getActualShipDate()) : null);
            pstmt.setInt(4, currentOrder.getWarehouseId());
            pstmt.setString(5, currentOrder.getOrderStatus());
            pstmt.setString(6, currentOrder.getPaymentStatus());
            pstmt.setBigDecimal(7, currentOrder.getTaxAmount());
            pstmt.setBigDecimal(8, currentOrder.getDiscountAmount());
            pstmt.setBigDecimal(9, currentOrder.getTotalAmount());
            pstmt.setBigDecimal(10, currentOrder.getPaidAmount());
            pstmt.setString(11, currentOrder.getNotes());
            pstmt.setTimestamp(12, Timestamp.valueOf(LocalDateTime.now()));
            pstmt.setInt(13, currentOrder.getOrderId());

            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected == 0) {
                throw new SQLException("更新订单失败，未找到记录。");
            }
        } catch (SQLException e) {
            throw new RuntimeException("数据库操作失败: " + e.getMessage(), e);
        } finally {
            DBUtils.closeAll(conn, pstmt, null);
        }
    }

    /**
     * 验证表单数据
     */
    private boolean validateForm() {
        // 验证仓库ID
        if (!validateNumericField(warehouseIdField, "仓库ID")) return false;

        // 验证下单日期
        if (!validateDateTimeField(orderDateField, "下单日期")) return false;

        // 验证预计发货日期
        if (!expectedShipDateField.getText().trim().isEmpty() && !validateDateField(expectedShipDateField, "预计发货日期")) return false;

        // 验证实际发货日期
        if (!actualShipDateField.getText().trim().isEmpty() && !validateDateField(actualShipDateField, "实际发货日期")) return false;

        // 验证金额字段
        if (!taxAmountField.getText().trim().isEmpty() && !validateDecimalField(taxAmountField, "税额")) return false;
        if (!discountAmountField.getText().trim().isEmpty() && !validateDecimalField(discountAmountField, "折扣金额")) return false;
        if (!validateDecimalField(totalAmountField, "总金额")) return false;
        if (!paidAmountField.getText().trim().isEmpty() && !validateDecimalField(paidAmountField, "已付金额")) return false;

        // 验证总金额是否正确
        try {
            BigDecimal taxAmount = taxAmountField.getText().trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(taxAmountField.getText().trim());
            BigDecimal discountAmount = discountAmountField.getText().trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(discountAmountField.getText().trim());
            BigDecimal totalAmount = new BigDecimal(totalAmountField.getText().trim());
            
            // 调用现有的updateTotalAmount方法确保计算一致性
            updateTotalAmount();
            BigDecimal recalculatedTotal = new BigDecimal(totalAmountField.getText().trim());
            
            if (recalculatedTotal.compareTo(totalAmount) != 0) {
                int option = JOptionPane.showConfirmDialog(this,
                        "总金额与计算值不符（计算值=" + recalculatedTotal + "），是否自动修正？",
                        "金额不一致",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE);
                if (option == JOptionPane.YES_OPTION) {
                    // updateTotalAmount已经更新了文本框，不需要再次设置
                } else {
                    // 用户不想修正，将值改回原来的
                    totalAmountField.setText(totalAmount.toString());
                    return false;
                }
            }
        } catch (NumberFormatException e) {
            // 忽略，因为前面已经验证过数字格式
        }
        
        // 验证已付金额不大于总金额
        try {
            if (!paidAmountField.getText().trim().isEmpty()) {
                BigDecimal totalAmount = new BigDecimal(totalAmountField.getText().trim());
                BigDecimal paidAmount = new BigDecimal(paidAmountField.getText().trim());
                
                if (paidAmount.compareTo(totalAmount) > 0) {
                    showWarning("已付金额不能大于总金额");
                    paidAmountField.requestFocus();
                    return false;
                }
            }
        } catch (NumberFormatException e) {
            // 忽略，因为前面已经验证过数字格式
        }

        return true;
    }

    private boolean validateNumericField(JTextField field, String fieldName) {
        String value = field.getText().trim();
        if (value.isEmpty()) {
            showWarning(fieldName + "不能为空");
            field.requestFocus();
            return false;
        }
        try {
            Integer.parseInt(value);
        } catch (NumberFormatException e) {
            showWarning(fieldName + "必须是数字");
            field.requestFocus();
            return false;
        }
        return true;
    }

    private boolean validateDateTimeField(JTextField field, String fieldName) {
        String value = field.getText().trim();
        if (value.isEmpty()) {
            showWarning(fieldName + "不能为空");
            field.requestFocus();
            return false;
        }
        try {
            LocalDateTime.parse(value, DATETIME_FORMATTER);
        } catch (DateTimeParseException e) {
            showWarning(fieldName + "格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
            field.requestFocus();
            return false;
        }
        return true;
    }

    private boolean validateDateField(JTextField field, String fieldName) {
        String value = field.getText().trim();
        try {
            LocalDate.parse(value, DATE_FORMATTER);
        } catch (DateTimeParseException e) {
            showWarning(fieldName + "格式不正确，请使用yyyy-MM-dd格式");
            field.requestFocus();
            return false;
        }
        return true;
    }

    private boolean validateDecimalField(JTextField field, String fieldName) {
        String value = field.getText().trim();
        if (value.isEmpty()) {
            showWarning(fieldName + "不能为空");
            field.requestFocus();
            return false;
        }
        try {
            new BigDecimal(value);
        } catch (NumberFormatException e) {
            showWarning(fieldName + "必须是有效的数字");
            field.requestFocus();
            return false;
        }
        return true;
    }

    /**
     * 清空表单
     */
    private void clearForm() {
        orderDateField.setText("");
        expectedShipDateField.setText("");
        actualShipDateField.setText("");
        warehouseIdField.setText("");
        orderStatusCombo.setSelectedIndex(0);
        paymentStatusCombo.setSelectedIndex(0);
        taxAmountField.setText("");
        discountAmountField.setText("");
        totalAmountField.setText("");
        paidAmountField.setText("");
        notesArea.setText("");
    }


    // 组件淡入效果
    private void fadeInComponent(final JComponent component) {
        final Timer timer = new Timer(20, null);
        final float[] opacity = {0.0f};
        
        timer.addActionListener(e -> {
            opacity[0] += 0.05f;
            if (opacity[0] >= 1.0f) {
                opacity[0] = 1.0f;
                timer.stop();
            }
            component.setOpaque(false);
            component.repaint();
        });
        
        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(UpdateSalesOrder::new);
    }
} 
